package com.easy.threads.actuator;


import com.easy.common.IWork;
import com.easy.threads.factory.ThreadFactory;
import com.easy.threads.singleton.Constant;
import com.easy.utils.PartitionJobStatus;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 描述: 任务仓库
 *
 * @author gwj
 * @date 2023年12月14日 14:52
 */

public final class Warehouse {


    private static final Map<String,CopyOnWriteArrayList<IWork>> WORK_PARTITION = new ConcurrentHashMap<>(50);


    /**
     * 描述 : 获取任务
     * @author gwj
     * @date 2023/12/14 14:58
     * @param partition 任务所属分区KEY
     * @return com.easy.common.IWork
     */
    public IWork getWork(String partition){
        List<IWork> iWorks = WORK_PARTITION.get(partition);
        if(iWorks == null){
            return null;
        }
        return !iWorks.isEmpty() ?iWorks.remove(0):null;
    }

    /**
     * 描述 : 添加任务
     * @author gwj
     * @date 2023/12/14 15:45
     * @param workList 任务集合
     * @param partition 任务所属分区
     */
    public synchronized void addWork(List<IWork> workList, String partition){

        if(!checkPartitionStatus(partition)){
            throw new RuntimeException("当前任务分区即将关闭,无法添加新任务");
        }

        int maxQueueLength = ThreadFactory.getMaxQueueLength(partition);
        List<IWork> iWorks = WORK_PARTITION.get(partition);
        if(iWorks != null){
            if((workList.size()+iWorks.size()) > maxQueueLength){
                throw new RuntimeException("任务数量超出任务队列最大容量，当前分区任务最大容量:"+ maxQueueLength);
            }
            iWorks.addAll(workList);
            return;
        }
        if(workList.size() > maxQueueLength){
            throw new RuntimeException("任务数量超出任务队列最大容量，当前分区任务最大容量:"+ maxQueueLength);
        }
        CopyOnWriteArrayList<IWork> work = new CopyOnWriteArrayList<>(workList);
        WORK_PARTITION.put(partition,work);

    }

    public Map<String,CopyOnWriteArrayList<IWork>> getWorkList(){
        return WORK_PARTITION;

    }

    public  void addWork(List<IWork> workList){
        this.addWork(workList, Constant.WORK_PARTITION_DEFAULT);
    }


    private boolean checkPartitionStatus(String partition){
       return PartitionJobStatus.getStatus(partition);
    }

    private void containsTask(List<IWork> workList){

    }
}
